package com.example.meetsmart.controller;

import com.example.meetsmart.model.Room;
import com.example.meetsmart.service.RoomService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/api/rooms")
public class RoomController {
    private final RoomService roomService;

    public RoomController(RoomService roomService) {
        this.roomService = roomService;
    }

    @GetMapping
    public ResponseEntity<Page<Room>> getAllRooms(Pageable pageable) {
        return ResponseEntity.ok((Page<Room>) roomService.getAllRooms(pageable));
    }

    @GetMapping("/active")
    public ResponseEntity<Page<Room>> getActiveRooms(Pageable pageable) {
        return ResponseEntity.ok((Page<Room>) roomService.getActiveRooms(pageable));
    }

    @GetMapping("/{id}")
    public ResponseEntity<Room> getRoomById(@PathVariable Long id) {
        return ResponseEntity.ok(roomService.getRoomById(id));
    }

    @PostMapping
    @PreAuthorize("hasRole('ADMIN') or hasRole('MODERATOR')")
    public ResponseEntity<Room> createRoom(@Valid @RequestBody Room room) {
        return ResponseEntity.ok(roomService.createRoom(room));
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('MODERATOR')")
    public ResponseEntity<Room> updateRoom(@PathVariable Long id, @Valid @RequestBody Room roomDetails) {
        return ResponseEntity.ok(roomService.updateRoom(id, roomDetails));
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Void> deleteRoom(@PathVariable Long id) {
        roomService.deleteRoom(id);
        return ResponseEntity.noContent().build();
    }

    @GetMapping("/available")
    public ResponseEntity<List<Room>> findAvailableRooms(
            @RequestParam LocalDateTime startTime,
            @RequestParam LocalDateTime endTime,
            @RequestParam(required = false) Integer capacity,
            @RequestParam(required = false) Boolean hasProjector,
            @RequestParam(required = false) Boolean hasWhiteboard,
            @RequestParam(required = false) Boolean hasAudioSystem) {

        if (capacity != null || hasProjector != null || hasWhiteboard != null || hasAudioSystem != null) {
            return ResponseEntity.ok(roomService.findAvailableRoomsWithCriteria(
                    capacity != null ? capacity : 1,
                    hasProjector != null ? hasProjector : false,
                    hasWhiteboard != null ? hasWhiteboard : false,
                    hasAudioSystem != null ? hasAudioSystem : false));
        } else {
            return ResponseEntity.ok(roomService.findAvailableRoomsBetweenTimes(startTime, endTime));
        }
    }
}